import { defineStore } from 'pinia'
import { AuraTheme } from '@/theme/appTheme/AuraTheme'
import { LaraTheme } from '@/theme/appTheme/LaraTheme'
import { MaterialTheme } from '@/theme/appTheme/MaterialTheme'
import { NoraTheme } from '@/theme/appTheme/NoraTheme'
import { $t, $dt, usePreset } from '@primevue/themes'

export const themesList = {
  Aura: AuraTheme,
  Lara: LaraTheme,
  Material: MaterialTheme,
  Nora: NoraTheme,
} as const

interface TokenItem {
  token: string
  label: string
  variable: string
  value: string
  isColor: boolean
}

export type ThemeNames = keyof typeof themesList
export type Theme = (typeof themesList)[ThemeNames]

// 深拷贝函数
export function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

export const useThemeStore = defineStore('theme', {
  state: () => ({
    CurrentTheme: deepClone(themesList.Aura) as Theme,
    TempTheme: deepClone(themesList.Aura) as Theme,
    acTokens: [] as TokenItem[],
    Scale: 14, // 基础字体大小
  }),
  getters: {},
  actions: {
    // 初始化TempTheme
    initTempTheme() {
      this.TempTheme = deepClone(this.CurrentTheme)
      this.setScale(this.Scale)
    },

    // 预览主题
    PreviewTheme() {
      // console.log('预览主题', this.TempTheme)
      // $t().preset(this.TempTheme).use({ useDefaultOptions: true })
      usePreset(this.TempTheme)
    },

    // 重置TempTheme
    ResetTheme() {
      this.TempTheme = deepClone(this.CurrentTheme)
      $t().preset(this.TempTheme).use({ useDefaultOptions: true })
    },

    // 应用主题
    ApplyTheme() {
      this.CurrentTheme = deepClone(this.TempTheme)
      $t().preset(this.CurrentTheme).use({ useDefaultOptions: true })
    },

    // 添加scale设置方法
    setScale(value: number) {
      // this.Scale = value
      document.documentElement.style.fontSize = `${value}px`
    },

    // 生成当前主题的动态token
    generateACTokens(parentPath: string | null, obj: Record<string, any>): void {
      // 跳过 dark 主题相关配置
      for (const key in obj) {
        if (key === 'dark') {
          continue
        }

        const specialKeys = ['primitive', 'semantic', 'colorScheme', 'light', 'extend']
        // 特殊关键字处理：直接递归处理其子属性
        if (specialKeys.includes(key)) {
          this.generateACTokens(null, obj[key])
        } else {
          // 普通属性处理：如果是对象，则递归处理其子属性
          if (typeof obj[key] === 'object') {
            const newPath = parentPath ? `${parentPath}.${key}` : key
            this.generateACTokens(newPath, obj[key])
          } else {
            // 普通属性处理：将驼峰命名转换为点命名，并获取其值
            const regex = /\.\d+$/
            const tokenName = this.camelCaseToDotCase(parentPath ? `${parentPath}.${key}` : key)
            const dtResult = $dt(tokenName)
            const tokenValue = dtResult.value
            const isColor = tokenName.includes('color') || tokenName.includes('background') || regex.test(tokenName)

            // 将获取到的token信息添加到 acTokens 数组中
            this.acTokens.push({
              token: tokenName,
              label: `{${tokenName}}`,
              variable: dtResult.variable,
              value: tokenValue,
              isColor,
            })
          }
        }
      }
    },

    // 将驼峰命名转换为点命名
    camelCaseToDotCase(name: string) {
      return name.replace(/([a-z])([A-Z])/g, '$1.$2').toLowerCase()
    },

    /**
     * 替换主题的颜色配置
     * - 将 emerald 设置为主要颜色
     * - 设置亮色主题的表面颜色（使用 slate 色板）
     * - 设置暗色主题的表面颜色（使用 zinc 色板）
     * - 保持表面颜色的 0 值为白色
     */
    replaceColorPalette() {
      // 设置主要颜色为 emerald
      this.TempTheme.semantic.primary = this.TempTheme.primitive.emerald

      // 设置亮色主题的表面颜色
      this.TempTheme.semantic.colorScheme.light.surface = {
        0: '#ffffff', // 保持白色背景
        ...this.TempTheme.primitive.slate, // 使用 slate 色板
      }

      // 设置暗色主题的表面颜色
      this.TempTheme.semantic.colorScheme.dark.surface = {
        0: '#ffffff', // 保持白色背景
        ...this.TempTheme.primitive.zinc, // 使用 zinc 色板
      }

      // 应用更改
      this.PreviewTheme()
    },
  },
  persist: {
    pick: ['CurrentTheme', 'Scale'],
  },
})
